package com.wei.web.middleware.httpfilter.registrar.handler;

import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.expression.BeanFactoryResolver;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.SpelParseException;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class ExpressionHandler {
    private StandardEvaluationContext context;
    private ExpressionParser parser;

    public ExpressionHandler(ApplicationContext applicationContext) {
        context = new StandardEvaluationContext();
        context.setBeanResolver(new BeanFactoryResolver(applicationContext));
        parser = new SpelExpressionParser();
    }

    public List<String> evaluateValue(List<String> expressionStrings) {
        List<String> result = new ArrayList<>();
        for (String expressionStr : expressionStrings) {
            try {
                List<String> expressionResult = doEvaluateExpressionStr(expressionStr);
                result.addAll(expressionResult);
            } catch (SpelParseException e) {
                result.add(expressionStr);
            }
        }
        return result;
    }

    public String evaluateValue(String expressionString) {
        try {
            List<String> expressionResult = doEvaluateExpressionStr(expressionString);
            return expressionResult.get(0);
        } catch (SpelParseException e) {
            return expressionString;
        }
    }

    private List<String> doEvaluateExpressionStr(String expressionString) {
        if (expressionString.startsWith("T(") || expressionString.startsWith("#") || expressionString.startsWith("$")) {
            return parser.parseExpression(expressionString).getValue(context, List.class);
        }
        return Arrays.asList(expressionString);
    }
}
